
package uk.ac.cam.cl.oscar;

import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.media.jai.*;
import javax.swing.*;

public class ImageConverter {

	/** GASH converted of PlanarImages
	 * Heavily inspired by ImageDisplay.java by
	 *
	 * @author Daniel Rice
	 * @author Dennis Sigel
	 */
	public static BufferedImage toBuffered (PlanarImage source)
	{
		ColorModel colorModel = source.getColorModel();
		SampleModel sampleModel = source.getSampleModel();
		
        if (colorModel == null) {
            // If not, then create one.
            colorModel = PlanarImage.createColorModel(sampleModel);
            if (colorModel == null) {
                throw new IllegalArgumentException("no color model");
            }
        }
		
		// assert (source.getNumXTiles() * source.getNumYTiles() == 1);
	
		Raster tile = source.getTile(0, 0);

		DataBuffer dataBuffer = tile.getDataBuffer();
		WritableRaster wr = tile.createWritableRaster(sampleModel,
                                                      dataBuffer,
                                                      null);
                                                      
		return new BufferedImage(colorModel, wr, colorModel.isAlphaPremultiplied(), null);

    }
}